<template>
  <div>
    <x-search>
      <template #search>
        <p>
          角色名称
          <a-input
            v-model:value="searchParams.name"
            placeholder="请输入角色名称"
            style="width: 150px"
          />
        </p>
        <p style="margin-left: 10px">
          角色编码
          <a-input
            v-model:value="searchParams.code"
            placeholder="请输入角色编码"
            style="width: 150px"
          />
        </p>
        <a-button
          type="primary"
          style="margin-left: 10px"
          @click="handleSearch"
        >
          搜索
        </a-button>
        <a-button style="margin-left: 10px" @click="resetSearch">
          重置
        </a-button>
      </template>
      <template #operate>
        <a-button
          type="primary"
          style="margin-left: 10px"
          @click="showAddModal"
          v-checkpermission="'role_add'"
        >
          <plus-outlined style="margin-right: 0" />
          新增角色
        </a-button>
      </template>
    </x-search>

    <!-- 新增角色弹窗 -->
    <a-modal
      v-model:open="addModalVisible"
      title="新增角色"
      @ok="handleAddSubmit"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="formRules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 13 }"
      >
        <a-form-item label="角色名" name="name">
          <a-input v-model:value="addForm.name" placeholder="请输入角色名" />
        </a-form-item>
        <a-form-item label="角色编码" name="code">
          <a-input v-model:value="addForm.code" placeholder="请输入角色编码" />
        </a-form-item>
        <a-form-item label="角色描述" name="description">
          <a-input
            v-model:value="addForm.description"
            placeholder="请输入角色描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 角色表格 -->
    <a-table
      :dataSource="tableData"
      :columns="columns"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ y: 600 }"
      v-checkpermission="'role_list'"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <span>
            <a-button
              type="link"
              style="width: 50px; color: #1890ff"
              @click="showEditModal(record)"
              v-checkpermission="'role_edit'"
            >
              <EditOutlined style="margin-right: 0" />
              编辑
            </a-button>
            <a-button
              type="link"
              danger
              style="width: 80px; color: #cf1322"
              @click="handleDelete(record.id)"
              v-checkpermission="'role_delete'"
            >
              <DeleteOutlined style="margin-right: 0" />
              删除
            </a-button>
            <a-button
              type="link"
              danger
              style="width: 100px; color: #1890ff"
              @click="showPermissionModal(record.id)"
              v-checkpermission="'permiss_set'"
            >
              <EditOutlined style="margin-right: 0" />
              权限分配
            </a-button>
          </span>
        </template>
      </template>
    </a-table>

    <!-- 编辑角色弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="修改角色"
      @ok="handleEditSubmit"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 13 }"
      >
        <a-form-item label="角色名" name="name">
          <a-input v-model:value="editForm.name" />
        </a-form-item>
        <a-form-item label="角色描述" name="description">
          <a-input v-model:value="editForm.description" />
        </a-form-item>
        <a-form-item label="角色编码" name="code">
          <a-input v-model:value="editForm.code" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 权限设置弹窗 -->
    <a-modal
      v-model:open="permissionModalVisible"
      title="权限设置"
      @ok="handlePermissionSubmit"
    >
      <!-- <a-cascader
        v-model:value="selectedPermissions"
        style="width: 100%"
        multiple
        max-tag-count="responsive"
        :options="permissionOptions"
        placeholder="请选择权限"
      /> -->
      <a-tree
        v-model:checkedKeys="selectedPermissions"
        checkable
        :tree-data="permissionOptions"
        :field-names="{ key: 'value', title: 'label' }"
        :selectable="false"
        show-line
        style="width: 100%"
        placeholder="请选择权限"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";

import XSearch from "../components/XSearch.vue";
import http from "../http/http";
import { useStore } from "vuex";
import dayjs from "dayjs";
import type { CascaderProps } from "ant-design-vue";

const store = useStore();

// 权限指令
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!store.state.userPermiss.includes(binding.value)) {
      el.parentNode?.removeChild(el);
    }
  },
};

// 搜索相关
const searchParams = reactive({
  name: "",
  code: "",
});

const resetSearch = () => {
  searchParams.name = "";
  searchParams.code = "";
  fetchRoles();
};

const handleSearch = () => {
  pagination.current = 1;
  fetchRoles();
};

// 表格相关
const columns = [
  { title: "角色名称", dataIndex: "name", key: "name", width: 100 },
  { title: "描述", dataIndex: "description", key: "description", width: 200 },
  { title: "创建时间", dataIndex: "createdAt", key: "createdAt", width: 180 },
  { title: "操作", key: "action", width: 200 },
];

const tableData = ref([]);
const pagination = reactive({
  pageSize: 5,
  total: 0,
  current: 1,
});

const handleTableChange = (pag: any) => {
  pagination.pageSize = pag.pageSize;
  pagination.current = pag.current;
  fetchRoles();
};

const fetchRoles = async () => {
  try {
    const response = await http.get("/api/roles/list", {
      params: {
        name: searchParams.name,
        rolecode: searchParams.code,
        page_size: pagination.pageSize,
        page: pagination.current,
      },
    });

    tableData.value = response.data.data.roles.map((role: any) => ({
      ...role,
      createdAt: dayjs(role.createtime).format("YYYY-MM-DD HH:mm:ss"),
      key: role.id,
    }));

    pagination.total = response.data.data.total;
  } catch (error) {
    console.error("获取角色列表失败:", error);
    message.error("获取角色列表失败");
  }
};

// 新增角色相关
const addModalVisible = ref(false);
const addFormRef = ref();
const addForm = reactive({
  name: "",
  code: "",
  description: "",
});

const showAddModal = () => {
  addModalVisible.value = true;
};
// 橘色的添加
const handleAddSubmit = () => {
  addFormRef.value
    .validate()
    .then(async () => {
      try {
        const response = await http.post("/api/roles/addrole", {
          name: addForm.name,
          description: addForm.description,
          rolecode: addForm.code,
        });

        message.success(response.data.msg);
        addModalVisible.value = false;
        addFormRef.value.resetFields();
        fetchRoles();
      } catch (error) {
        console.error("添加角色失败:", error);
        message.error("添加角色失败");
      }
    })
    .catch((error: any) => console.log("表单验证失败", error));
};

// 编辑角色相关
const editModalVisible = ref(false);
const editFormRef = ref();
const editForm = reactive({
  id: 0,
  name: "",
  code: "",
  description: "",
});

const showEditModal = async (record: any) => {
  console.log(record);
  editModalVisible.value = true;
  editForm.id = record.id;
  editForm.name = record.name;
  editForm.description = record.description;
  editForm.code = record.role_code;

  //   try {
  //   const response = await http.get("/api/roles/edit_get", {
  //     params: { id }
  //   });

  //   const roleData = response.data.results[0];

  // } catch (error) {
  //   console.error("获取角色信息失败:", error);
  //   message.error("获取角色信息失败");
  // }
};

const handleEditSubmit = () => {
  editFormRef.value
    .validate()
    .then(async () => {
      try {
        const response = await http.post("/api/roles/edit_set", {
          id: editForm.id,
          name: editForm.name,
          description: editForm.description,
          rolecode: editForm.code,
        });

        message.success(response.data.msg);
        editModalVisible.value = false;
        fetchRoles();
      } catch (error) {
        console.error("修改角色失败:", error);
        message.error("修改角色失败");
      }
    })
    .catch((error: any) => console.log("表单验证失败", error));
};

// 删除角色
const handleDelete = (id: number) => {
  Modal.confirm({
    title: "删除角色",
    // icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要删除此角色吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        const response = await http.get("/api/role/delete_t", {
          params: { id },
        });
        message.success(response.data.msg);
        fetchRoles();
      } catch (error) {
        console.error("删除角色失败:", error);
        message.error("删除角色失败");
      }
    },
  });
};

// 权限设置相关
const permissionModalVisible = ref(false);
const selectedPermissions = ref([]);
let permissionOptions: CascaderProps["options"] = [];
// const permissionOptions = ref([]);
const currentRoleId = ref(0);
interface PermissionItem {
  id: number;
  name: string;
  permission_code: string;
}

interface TreeNode {
  value: string; // 节点唯一标识（对应 field-names 的 key）
  label: string; // 显示文本（对应 field-names 的 title）
  children?: TreeNode[];
  originData?: any; // 原始数据（可选）
}
// 全部权限的接口
const all_permission = async () => {
  try {
    const results = await http.get("/api/permissions/all");
    console.log(results);
    // 使用 Map 实现高效分组
    const groupMap = new Map<string, TreeNode>();

    results.data.results.forEach((item:any) => {
      const parentName = item.name.slice(0, 4);
      const parentValue = `P+${item.permission_code}`;

      if (!groupMap.has(parentName)) {
        groupMap.set(parentName, {
          value: parentValue,
          label: parentName,
          children: [],
        });
      }

      groupMap.get(parentName)?.children?.push({
        value: item.permission_code,
        label: item.name,
        originData: item, // 保留原始数据
      });
    });

    permissionOptions = Array.from(groupMap.values());
    console.log("权限树数据:", permissionOptions);
    console.log("permissionOptions.value", permissionOptions);
  } catch (error) {
    console.error("权限获取失败:", error);
    message.error("权限获取失败");
  }
};
const showPermissionModal = async (id: number) => {
  await all_permission();
  currentRoleId.value = id;
  permissionModalVisible.value = true;
  try {
    const results = await http.get("/api/roles/pression_get", {
      params: {
        role_id: id,
      },
    });
    console.log(results);
    // selectedPermissions.value = results.data.results.map((item: any) =>
    //   [item.id],
    // );
    selectedPermissions.value = results.data.results.map(
      (item: any) => item.id
    );

    // selectedPermissions.value = all_permission
    // permissionOptions.value = all_permission_option
    console.log("1111111111111111", selectedPermissions.value);
  } catch (error) {
    console.error("权限获取失败:", error);
    message.error("权限获取失败");
  }
};

const handlePermissionSubmit = () => {
  console.log("22222222222222222", selectedPermissions.value);
  if (selectedPermissions.value.length === 0) {
    message.warning("请至少选择一种权限");
    return;
  }

  // const permissionIds = selectedPermissions.value
  //   .map((item) => item[0])
  //   .join(",");
  const permissionIds = selectedPermissions.value.map((item) => item).join(",");
  console.log(permissionIds);
  // http
  //   .get("/api/roles/set_permission", {
  //     params: {
  //       id: currentRoleId.value,
  //       expression_ids: permissionIds,
  //     },
  //   })
  //   .then((response: any) => {
  //     message.success("权限设置成功");
  //     permissionModalVisible.value = false;
  //   })
  //   .catch((error: any) => {
  //     console.error("权限设置失败:", error);
  //     message.error("权限设置失败");
  //   });
};

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: "请输入角色名字", trigger: "change" },
    { min: 2, max: 10, message: "长度为2到10个字符串", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入角色描述", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入角色编码", trigger: "change" },
    { min: 2, max: 15, message: "长度为2到15个字符串", trigger: "blur" },
  ],
};

onMounted(() => {
  fetchRoles();
  // all_permission()
});
</script>

<style scoped>
:deep(.ant-btn > .anticon + span),
:deep(.ant-btn > span + .anticon) {
  margin-inline-start: 0;
}
</style>